package com.merchant.home;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.merchant.base.ExitApplication;
import com.merchant.constant.Constants;
import com.merchant.json.ReadJson;
import com.merchant.log.MyLogActivity;
import com.merchant.manage.MerchantManageActivity;
import com.merchant.my.MerchantMyActivity;
import com.merchant.my.MerchantPropagandaActivity;
import com.merchant.my.MerchantPropagandaZhifuActivity;
import com.merchant.my.VipActivity;
import com.merchant.popupwindow.NPopupWindow;
import com.merchant.popupwindow.NoticePopupWindow;
import com.merchant.popupwindow.PropagandaPopupWindow;
import com.merchant.popupwindow.XieyiPopupWindow;
import com.merchant.util.LoadingDialog;
import com.merchant.util.UpdateVersionService;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.merchant.activity.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

/**
 * 食尚男女商家版首页
 * 
 * @author chenwei
 * 
 * 
 */
public class MyHomeActivity extends Activity implements OnClickListener,
		OnRefreshListener {
	private ViewPager viewPager; // android-support-v4中的滑动组件
	private List<ImageView> imageViews; // 滑动的图片集合
	private int[] imageResId; // 图片ID
	private List<View> dots; // 图片标题正文的那些点
	private int currentItem = 0; // 当前图片的索引号
	private ScheduledExecutorService scheduledExecutorService;
	private ImageButton merchant_home_takemoney;
	// private FrameLayout touist_home;// 游客
	// private FrameLayout member_home;// 会员
	// private FrameLayout cumulative_gain_home;// 累计收益
	private FrameLayout cumulative_order_home;// 累计订单
	private FrameLayout cumulative_operating_income;// 累计营业收入
	private FrameLayout cumulative_consumption;// 累计消费金额
	// private LinearLayout merchant_manage_layout;// 经营
	// private LinearLayout merchant_my_layout;// 我的
	private FrameLayout bussness_income_ll;// 营业收入
	// private FrameLayout operating_income_ll;// 收益
	// private FrameLayout backmoney_cy_frame_layout;
	// private FrameLayout jbtx_framelayout;
	// private LinearLayout ll_fanxian;// 返现提现4.8
	// private LinearLayout merchant_huiyuan;//
	// private ImageButton bussiness_gain_ibt;
	// private ImageButton bussiness_income_ibt;
	// private TextView touist_number;
	// private TextView memeber_number;
	private TextView cumulative_consumption_home;
	private TextView cumulative_gain_homeo;
	// private TextView cumulative_gain;
	private TextView can_raise_cash_income;// 可提现营业收入
	// private TextView can_carry_cash_proceeds;// 可提现收益金额
	// private TextView fanxian_money;// 消费币提现
	// private TextView cy_back_money;// 返现
	// private TextView jbtx_text;// 9.8返现提现
	// private FrameLayout fanxian_income_ll;
	private HashMap<String, Object> mMap;
	private HashMap<String, Object> mUserMapLists;
	private ArrayList<HashMap<String, Object>> mDataList;
	private ArrayList<HashMap<String, Object>> DataList;
	private ArrayList<HashMap<String, Object>> DDataList;
	private ArrayList<HashMap<String, Object>> DDataListt;
	private ArrayList<HashMap<String, Object>> BydateDataList;
	private ArrayList<HashMap<String, Object>> CuurrentDataList;
	private HashMap<String, Object> XcDataList;
	private TextView my_title_text;
	boolean isExit;
	private NoticePopupWindow mNoticePopupWindow;
	private UpdateVersionService updateVersionService;
	private XieyiPopupWindow xieyipop;
	private PropagandaPopupWindow propagandaPop;
	private String name = null;
	private LoadingDialog dialog;
	private Timer timer;
	private SwipeRefreshLayout mSwipeLayout;
	long hours;
	long minutes;
	public static long time;
	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		ExitApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_merchant_home);
		dialog = new LoadingDialog(this);
		dialog.show();
		init();
		// "bzj":-1为未交保证金,0为己到期,1-11为还有多少个月到期
		if (Constants.bzj != null) {
			if (Constants.bzj.equals("-1")) {
				handler1.sendEmptyMessageDelayed(9, 100);
			} else if (Constants.bzj.equals("0")) {
				handler1.sendEmptyMessageDelayed(9, 100);
			}
		} else {
			handler1.sendEmptyMessageDelayed(9, 100);
		}
		// new Thread(GetCreatePayOrder).start();
		new Thread(getnotice).start();
		// new Thread(startUpdateRun).start();
		imageResId = new int[] { R.drawable.title_1, R.drawable.title2,
				R.drawable.title3 };
		imageViews = new ArrayList<ImageView>();
		// 初始化图片资源
		for (int i = 0; i < imageResId.length; i++) {
			ImageView imageView = new ImageView(this);
			imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			imageViews.add(imageView);
		}
		dots = new ArrayList<View>();
		dots.add(findViewById(R.id.v_dot0));
		dots.add(findViewById(R.id.v_dot1));
		dots.add(findViewById(R.id.v_dot2));
		viewPager = (ViewPager) findViewById(R.id.vp);
		viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
		// 设置一个监听器，当ViewPager中的页面改变时调用
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
		handler1.sendEmptyMessageDelayed(6, 100);
		mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.home_swipe_ly);

		mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorSchemeResources(android.R.color.holo_green_dark,
				android.R.color.holo_green_light,
				android.R.color.holo_orange_light,
				android.R.color.holo_orange_dark);

	}

	private void init() {
		cumulative_operating_income = (FrameLayout) findViewById(R.id.cumulative_operating_income_frame_layout);
		cumulative_consumption = (FrameLayout) findViewById(R.id.cumulative_consumption_frame_layout);
		cumulative_consumption_home = (TextView) findViewById(R.id.cumulative_consumption_home);
		cumulative_gain_homeo = (TextView) findViewById(R.id.cumulative_gain_home);
		can_raise_cash_income = (TextView) findViewById(R.id.can_raise_cash_income);
		bussness_income_ll = (FrameLayout) findViewById(R.id.bussness_income_ll);
		my_title_text = (TextView) findViewById(R.id.my_title_text);
		my_title_text.setText(Constants.merchantname);
		cumulative_operating_income.setOnClickListener(this);
		cumulative_consumption.setOnClickListener(this);
		bussness_income_ll.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {

		// 营业收入
		case R.id.bussness_income_ll:
			intent.setClass(getApplicationContext(),
					BussnessTakeMoneyActivity.class);
			if (mMap != null && mMap.size() > 0) {
				if (mMap.get("AvailableBalance") != null
						&& !mMap.get("AvailableBalance").toString()
								.equals("0")) {
					intent.putExtra("money2",
							mMap.get("AvailableBalance").toString());
				} else {
					intent.putExtra("money2", "0.00");
				}
			}
			startActivity(intent);
			break;
		// 营业总收入
		case R.id.cumulative_consumption_frame_layout:
			intent.setClass(getApplicationContext(),
					CumulativeConsumptionActivity.class);
			if (mMap != null && mMap.size() > 0) {
				if (mMap.get("OrderMoney") != null) {
					intent.putExtra("consumption",
							mMap.get("OrderMoney").toString());
				} else {
					intent.putExtra("consumption", "0.00");
				}
			}
			startActivity(intent);
			break;
		// 营业纯收入
		case R.id.cumulative_operating_income_frame_layout:
			intent.setClass(getApplicationContext(),
					CumulativeOperatingIncomeActivity.class);
			if (mMap != null && mMap.size() > 0) {
				if (mMap.get("BusinessIncomeMoney") != null) {
					intent.putExtra("gain",
							mMap.get("BusinessIncomeMoney")
									.toString());
				} else {
					intent.putExtra("gain", "0.00");
				}
			}
			startActivity(intent);
			break;
		case R.id.merchant_manage_layout:
			intent.setClass(getApplicationContext(),
					MerchantManageActivity.class);
			startActivity(intent);
			break;
		case R.id.merchant_my_layout:
			intent.setClass(getApplicationContext(), MerchantMyActivity.class);
			startActivity(intent);
			break;
		}
	}

	public void onRefresh() {
		handler1.sendEmptyMessageDelayed(8, 2000);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		timer.cancel();
	}

	public class MyTask extends TimerTask {
		public void run() {
			// 每个一段时间你想要做的事
			new Thread(getincome).start();

		}
	}

	// 获取首页信息
	Runnable getincome = new Runnable() {

		@Override
		public void run() {
			try {
				String ss = "merchantUserId=" + Constants.Id;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetHomeData + sign + "&merchantUserId="
						+ Constants.Id;
				String json = ReadJson.readParse(str);
				mUserMapLists = Constants.getJson2Object(json);
				Log.i("mUserMapLists", mUserMapLists + "================");
				mMap = Constants.getJson2Object(mUserMapLists.get("Data")
						.toString());
				Log.i("mMap", mMap + "================");
				handler1.sendEmptyMessageDelayed(2, 0);
				dialog.dismiss();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				dialog.dismiss();
				handler1.sendEmptyMessageDelayed(7, 0);
				e.printStackTrace();
			}
		}
	};
	Runnable getnotice = new Runnable() {
		@Override
		public void run() {
			try {
				// long time = System.currentTimeMillis();
				String ss = "mtype=" + Constants.mtype;
				String sign = Constants.sortsStr(ss);
				String str = Constants.getnotice + sign + "&mtype="
						+ Constants.mtype;
				String json = ReadJson.readParse(str);
				mUserMapLists = Constants.getJson2Object(json);
				// Log.i("mUserMapLists", mUserMapLists + "================");
				DataList = Constants.getJsonArray(mUserMapLists.get("Data")
						.toString());
				Log.i("getnotice", DataList + "================");
				dialog.dismiss();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				dialog.dismiss();
				handler1.sendEmptyMessageDelayed(7, 0);
				e.printStackTrace();
			}
			if (DataList != null && DataList.size() > 0) {
				handler1.sendEmptyMessageDelayed(5, 100);
			}
		}
	};
	Handler handler1 = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// // Log.i("json", mDataList.get(0).get("jhnum").toString()
				// // + "================" + mDataList);
				// if (mDataList.get(0).get("nojhnum") != null) {
				// touist_number.setText(mDataList.get(0).get("nojhnum")
				// .toString());
				// } else {
				// touist_number.setText("0");
				// }
				// if (mDataList.get(0).get("jhnum") != null) {
				// memeber_number.setText(mDataList.get(0).get("jhnum")
				// .toString());
				// } else {
				// memeber_number.setText("0");
				// }
				break;
			// 累计消费金额
				
			case 2:
				Log.i("DDataList", mMap.get("OrderMoney").toString());
				if (mMap.get("OrderMoney") != null) {
					cumulative_consumption_home.setText(mMap.get("OrderMoney")
							.toString());
				} else {
					cumulative_consumption_home.setText("0.00");
				}
				if (mMap.get("BusinessIncomeMoney") != null) {
					cumulative_gain_homeo.setText(mMap.get(
							"BusinessIncomeMoney").toString());
				} else {
					cumulative_gain_homeo.setText("0.00");
				}
				if (mMap.get("AvailableBalance") != null
						&& !mMap.get("AvailableBalance").toString().equals("0")) {
					can_raise_cash_income.setText(mMap.get("AvailableBalance")
							.toString());
				} else {
					can_raise_cash_income.setText("0.00");
				}

				break;
			case 3:
				break;
			case 4:

				break;
			case 5:
				mNoticePopupWindow = new NoticePopupWindow(MyHomeActivity.this,
						DataList);
				mNoticePopupWindow.showAtLocation(cumulative_operating_income,
						Gravity.CENTER, 0, 0);
				break;
			case 6:
				SharedPreferences sp = getApplicationContext()
						.getSharedPreferences("MyPop", MODE_PRIVATE);
				if (sp != null) {
					sp.getString("pop", "");
					sp.getString(Constants.musername, "");
				}
				Log.i("pop",
						"++++++++++" + sp.getString(Constants.musername, ""));
				if (sp.getString("pop", "").equals("1")
						&& sp.getString("username", "").equals(
								Constants.username)) {
				} else if (!sp.getString(Constants.musername, "").equals(
						Constants.username)) {
					xieyipop = new XieyiPopupWindow(MyHomeActivity.this,
							itemClick);
					xieyipop.showAtLocation(cumulative_operating_income,
							Gravity.CENTER, 0, 0);
				}
				break;
			case 7:
				// Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
				// Toast.LENGTH_SHORT).show();
				Log.i("exception", "网络异常");
				break;
			case 8:
				// new Thread(signsRun).start();
				new Thread(getincome).start();
				// new Thread(getcymoney).start();
				// new Thread(getcurrentmoney).start();
				mSwipeLayout.setRefreshing(false);
				break;
			case 9:
				// SharedPreferences ssp = getApplicationContext()
				// .getSharedPreferences("MyPopp", MODE_PRIVATE);
				// if (ssp != null) {
				// ssp.getString("popp", "");
				// // ssp.getString(Constants.musername, "");
				// }
				// Log.i("popp", "++++++++++" + ssp.getString("popp", ""));
				// if (ssp.getString("popp", "").equals("3")) {
				// } else if (!ssp.getString("popp", "").equals("3")) {
				// propagandaPop = new PropagandaPopupWindow(
				// MyHomeActivity.this, itemClickt);
				// propagandaPop.showAtLocation(cumulative_operating_income,
				// Gravity.CENTER, 0, 0);
				// }
				break;
			}
		};
	};
	private OnClickListener itemClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.popup_reg_xieyi_to_confirm_text:
				SharedPreferences sp = getApplicationContext()
						.getSharedPreferences("MyPop", MODE_PRIVATE);
				Editor editor = sp.edit();
				editor.putString("pop", "1");
				editor.putString(Constants.musername, Constants.musername);
				editor.commit();
				xieyipop.dismiss();
				break;
			case R.id.popup_reg_xieyi_cancel_cancel_text:
				ExitApplication.getInstance().exit();
				xieyipop.dismiss();
				break;
			}
		}
	};

	// Runnable GetCreatePayOrder = new Runnable() {
	//
	// @Override
	// public void run() {
	// try {
	// String ss = "userId=" + Constants.Id;
	// String sign = Constants.sortsStr(ss);
	// String str = Constants.GetCreatePayOrder + sign + "&userId="
	// + Constants.Id;
	// String json = ReadJson.readParse(str);
	// mUserMapLists = Constants.getJson2Object(json);
	// XcDataList = Constants.getJson2Object(mUserMapLists.get("Data")
	// .toString());
	// Log.i("msg", "=======================" + mUserMapLists);
	// Log.i("msg",
	// "======================="
	// + XcDataList.get("money").toString()
	// + XcDataList.get("payid").toString());
	// Constants.money = XcDataList.get("money").toString();
	// Constants.payid = XcDataList.get("payid").toString();
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// handler1.sendEmptyMessageDelayed(7, 0);
	// e.printStackTrace();
	// }
	// }
	// };
	// private OnClickListener itemClickt = new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// Intent intent = new Intent();
	// switch (v.getId()) {
	// case R.id.check_parpagandao:
	// if (propagandaPop.mCheck.isChecked()) {
	// SharedPreferences ssp = getApplicationContext()
	// .getSharedPreferences("MyPopp", MODE_PRIVATE);
	// Editor editor = ssp.edit();
	// editor.putString("popp", "3");
	// // editor.putString(Constants.musername,
	// // Constants.musername);
	// editor.commit();
	// editor.clear();
	// } else {
	// SharedPreferences ssp = getApplicationContext()
	// .getSharedPreferences("MyPopp", MODE_PRIVATE);
	// Editor editor = ssp.edit();
	// editor.putString("popp", "2");
	// // editor.putString(Constants.musername,
	// // Constants.musername);
	// editor.commit();
	// editor.clear();
	// }
	// break;
	// case R.id.btn_propaganda:
	// // SharedPreferences sp = getApplicationContext()
	// // .getSharedPreferences("MyPop", MODE_PRIVATE);
	// // Editor editor = sp.edit();
	// // editor.putString("pop", "1");
	// // editor.putString(Constants.musername, Constants.musername);
	// // editor.commit();
	// // new Thread(GetCreatePayOrder).start();
	// intent.setClass(getApplicationContext(),
	// MerchantPropagandaZhifuActivity.class);
	// Log.i("Constants.money", "======================="
	// + Constants.money);
	// if (Constants.money != null) {
	// intent.putExtra("xc_money", Constants.money);
	// } else {
	// intent.putExtra("xc_money", "0.00");
	// }
	// intent.putExtra("username", Constants.payid);
	// startActivity(intent);
	// break;
	// case R.id.propaganda_continue_use:
	// // ExitApplication.getInstance().exit();
	// // if (time >= 0) {
	// propagandaPop.dismiss();
	// // } else {
	// // intent.setClass(getApplicationContext(),
	// // MyLogActivity.class);
	// // startActivity(intent);
	// // }
	// break;
	// case R.id.vip_btn:
	// intent.setClass(getApplicationContext(), VipActivity.class);
	// startActivity(intent);
	// // Toast.makeText(getApplicationContext(), "vip", 0).show();
	// break;
	// }
	// }
	// };

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void exit() {
		if (!isExit) {
			isExit = true;
			Toast.makeText(getApplicationContext(), "再按一次退出程序",
					Toast.LENGTH_SHORT).show();
			// 利用handler延迟发送更改状态信息
			mHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			ExitApplication.getInstance().exit();
			System.exit(0);
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			isExit = false;
		}

	};

	@Override
	protected void onStart() {
		timer = new Timer();
		MyTask task = new MyTask();
		timer.schedule(task, 0);// 开始时间Date型，周期long型豪秒级
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每四秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 4,
				TimeUnit.SECONDS);
		super.onStart();
	}

	@Override
	protected void onStop() {
		// 当Activity不可见的时候停止切换
		scheduledExecutorService.shutdown();
		super.onStop();
	}

	/**
	 * 换行切换任务
	 * 
	 * @author chenwei
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				System.out.println("currentItem: " + currentItem);
				currentItem = (currentItem + 1) % imageViews.size();
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author chenwei
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			currentItem = position;
			dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
			dots.get(position).setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 * @author chenwei
	 * 
	 */
	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageResId.length;
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

}
